class Solution(object):
    def findCircleNum(self, isConnected):
        n = len(isConnected)
        p = [i for i in range(n)]
        def find(x):
            if p[x] == x:
                return p[x]
            else:
                p[x] = find(p[x]) 
                return p[x]
            
        def union(x, y):
            rx = find(x)
            ry = find(y)
            if rx != ry:
                if rx < ry:
                    p[ry] = rx
                else:
                    p[rx] = ry

        for i in range(n):
            for j in range(i + 1, n):
                if isConnected[i][j]:
                    union(i, j)

        for i in range(n):
            p[i] = find(i)
        return len(set(p))